package com.honglang.struts2.action;

import java.io.File;
import java.io.IOException;
import java.util.List;

import org.apache.struts2.ServletActionContext;
import org.aspectj.util.FileUtil;

import com.honglang.aop.impl.UpdateFileSysAndPhotoInDB;
import com.honglang.common.tools.Constants;
import com.opensymphony.xwork2.Action;

public class UploadFileAction extends BaseAction {
	
	private String savePath;
	
	private List<File> fileList;

	private List<String> fileListFileName;
	
	
	
	/**
	 * upload file
	 * @return
	 */
	@UpdateFileSysAndPhotoInDB
	public String upload(){
		if(null != fileList){
			int length = fileList.size();
			for(int i=0 ;  i< length ; i++){
				
				try {
					if(Constants.ImageTypesList.contains(fileListFileName.get(i).substring(fileListFileName.get(i).lastIndexOf(".")+1).toLowerCase())){
						FileUtil.copyFile(fileList.get(i), new File(this.getSavePath() + "/" + Constants.ImageFileDir + "/" + fileListFileName.get(i)));
					}else{
						FileUtil.copyFile(fileList.get(i), new File(this.getSavePath() + "/" +  Constants.OtherFileDir + "/" + fileListFileName.get(i)));
					}
				} catch (IOException e) {
					this.getRequest().setAttribute("errorMsg", "error when uploading File");
					return Action.ERROR;
				}
			}
			this.getRequest().setAttribute("feedBack", "Upload Success");
		}else{
			this.getRequest().setAttribute("errorMsg", "File can't be empty");
		}
		
		return Action.SUCCESS;
	}
	

	public List<File> getFileList() {
		return fileList;
	}

	public void setFileList(List<File> fileList) {
		this.fileList = fileList;
	}

	public List<String> getFileListFileName() {
		return fileListFileName;
	}

	public void setFileListFileName(List<String> fileListFileName) {
		this.fileListFileName = fileListFileName;
	}

	
	public String getSavePath() {
		return ServletActionContext.getServletContext().getRealPath(this.savePath); 
	}

	public void setSavePath(String savePath) {
		this.savePath = savePath;
	}
	
	
}
